#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>

#include <iostream>

using namespace std;

#define PORT 8889
#define MAX_EVENTS 10

int main(int argc, char const *argv[]) {
  int s_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
  if (s_sockfd < 0) {
    perror("Error For socket");
    return 1;
  }
  int opt;
  setsockopt(s_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  struct sockaddr_in s_addr;
  bzero(&s_addr, sizeof(s_addr));
  s_addr.sin_family = AF_INET;
  s_addr.sin_port = htons(PORT);
  s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  if (bind(s_sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr)) < 0) {
    perror("Error For bind");
    return 1;
  }
  if (listen(s_sockfd, 5) < 0) {
    perror("Error For listen");
    return 1;
  }

  // 创建epoll句柄
  int epfd;
  if ((epfd = epoll_create(5)) < 0) {
    perror("Error For epoll_create");
    return 1;
  }
  // 创建服务器监听event
  struct epoll_event ev;
  ev = {.events = EPOLLIN, .data = {.fd = s_sockfd}};
  // 添加到epoll中
  if (epoll_ctl(epfd, EPOLL_CTL_ADD, s_sockfd, &ev) < 0) {
    perror("Error For epoll_ctl");
    return 1;
  }

  // 创建event数组
  struct epoll_event events[MAX_EVENTS];
  // 有效事件数量
  int num_fds;
  while (1) {
    // 监听有效事件
    num_fds = epoll_wait(epfd, events, MAX_EVENTS, -1);
    if (num_fds < 0) {
      perror("Error For epoll_wait");
      return 1;
    }
    // 遍历检测FD事件
    for (int i = 0; i < num_fds; ++i) {
      // 服务端接收客户端连接
      if (events[i].data.fd == s_sockfd) {
        struct sockaddr_in c_addr;
        socklen_t size = sizeof(c_addr);
        int c_sockfd = accept(s_sockfd, (struct sockaddr *)&c_addr, &size);
        if (c_sockfd < 0) {
          perror("Error For accept");
          return 1;
        }
        printf("NEW CLIENT CONNECTED [%s]\n", inet_ntoa(c_addr.sin_addr));
        // 监听客户端读事件
        ev.events = EPOLLIN;
        ev.data.fd = c_sockfd;
        if (epoll_ctl(epfd, EPOLL_CTL_ADD, c_sockfd, &ev) < 0) {
          perror("Error For epoll_ctl");
          return 1;
        }
      } else {
        // 客户端写事件
        int c_eventfd = events[i].data.fd;
        char buff[1024]{0};
        int n = read(c_eventfd, buff, sizeof(buff));
        if (n <= 0) {
          close(c_eventfd);
          printf("CLIENT DISCONNECT\n");
        } else {
          buff[n] = '\0';
          printf("RECV FROM CLIENT -> [%s]\n", buff);
        }
      }
    }
  }
  return 0;
}
